package org.luxor.commons.playwright.config;

import org.luxor.commons.playwright.client.PlaywrightClient;
import org.luxor.commons.playwright.client.impl.PlaywrightClientImpl;
import org.luxor.commons.playwright.component.PlaywrightBrowserCreator;
import org.luxor.commons.playwright.config.properties.PlaywrightProperties;
import org.luxor.commons.playwright.listener.AbstractPlaywrightEventListener;
import org.luxor.commons.playwright.listener.PlaywrightEventListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;


/**
 * playwright 全局配置
 *
 * @author Mr.Yan  @date: 2022/03/21
 */
@Configuration
@EnableConfigurationProperties(PlaywrightProperties.class)
@ConditionalOnProperty(prefix = PlaywrightProperties.PREFIX, name = "enabled", havingValue = "true", matchIfMissing = true)
public class PlaywrightAutoConfig {
    private static final Logger log = LoggerFactory.getLogger(PlaywrightAutoConfig.class);

    @Bean
    @ConditionalOnMissingBean(PlaywrightBrowserCreator.class)
    public PlaywrightBrowserCreator playwrightBrowserCreator(PlaywrightProperties playwrightProperties) {
        log.info("Initialize checks the instantiation of the playwright...");
        PlaywrightBrowserCreator browserCreator = new PlaywrightBrowserCreator(playwrightProperties);
        log.info("Initialize checks the instantiation of the playwright, complete");
        return browserCreator;
    }

    @Bean
    @ConditionalOnMissingBean(name = "defaultPlaywrightEventListener")
    public PlaywrightEventListener defaultPlaywrightEventListener() {
        return new AbstractPlaywrightEventListener();
    }

    @Bean
    @ConditionalOnMissingBean
    public PlaywrightClient playwrightClient(PlaywrightBrowserCreator playwrightBrowserCreator,
                                             PlaywrightProperties playwrightProperties,
                                             ObjectProvider<List<PlaywrightEventListener>> listeners) {
        log.info("Initialize the instantiation of playwrightClient...");
        PlaywrightClient playwrightClient = new PlaywrightClientImpl(playwrightBrowserCreator, playwrightProperties, listeners.getIfUnique());
        log.info("Initialize the instantiation of playwrightClient, complete");
        return playwrightClient;
    }

}
